package com.ocom.payhandle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.HttpUtils;
import com.ocom.common.entity.card.EntityXfAccountInfo;
import com.ocom.common.entity.card.EntityXfSignNo;
import com.ocom.common.entity.card.EntiyXfMerchPayInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.typehandler.SignNoHandle;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.ccb.CcbzhshAddUserVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payhandle.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Slf4j
@Service
public class CcbAccountServiceImpl implements CcbAccountService {

    //    @Value("${paycenter.url}")
//    private String payCenterUrl;
//    @Value("${pay.url}")
//    private String payUrl;
    @Resource
    private PersonnelInfoService personnelInfoService;
    @Resource
    private XfSignNoService xfSignNoService;
    @Resource
    private XfMerchPayInfoService xfMerchPayInfoService;
    @Resource
    private XfCardInfoService xfCardInfoService;
    @Resource
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public Result ccbzhshAddUser(Long comId, CcbzhshAddUserVo request) {
        EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(request.getComId(), 0L);
        if (entiyXfMerchPayInfo == null) {
            return ResultUtil.error(ResultEnum.Err_2031);
        }
        EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.getOnePersonInfo(request.getComId(), request.getPId());
        if (entityPersonnelInfo == null) {
//            ResultUtil.error(ResultEnum.Err_4014);
            return ResultUtil.error(ResultEnum.Err_303);
        }
//        if (StringUtil.isEmpty(entityPersonnelInfo.getData().toString())) {
//            ResultUtil.error(ResultEnum.Err_303);
//        }
//        JSONObject jsonPersonnelInfo = JSON.parseObject(JSON.toJSONString(entityPersonnelInfo.getData()));
        EntityXfSignNo entityXfSignNo = xfSignNoService.getUserSignInfo(request.getComId(), request.getPId(), -1, 32, -1);
//        if (entityXfSignNo == null || entityXfSignNo.getCode() != 200) {
//            ResultUtil.error(ResultEnum.Err_4014);
//        }
//        if (entityXfSignNo == null) {
//            return ResultUtil.error(ResultEnum.Err_303);
//        }
//        JSONObject jsonXfSignNo = JSON.parseObject(JSON.toJSONString(entityPersonnelInfo.getData()));
        HashMap<String, Object> map = new HashMap<>();
//        map.put("token", "Bearer " + SecurityUtils.getToken());
        map.put("companyId", entiyXfMerchPayInfo.getCompanyId());
        map.put("userName", entiyXfMerchPayInfo.getUserName());
        map.put("payPassword", entiyXfMerchPayInfo.getPassword());
        map.put("pCode", entityPersonnelInfo.getPCode());
        map.put("pName", entityPersonnelInfo.getPName());
        map.put("pSex", String.valueOf(entityPersonnelInfo.getPSex()));
        map.put("pPhone", entityPersonnelInfo.getPPhone());
        log.info("发送内容: {}", map);
        String strCustId = "";
        String payUrl = companyInfoService.getPayCenterUrl(request.getComId(), entiyXfMerchPayInfo.getCompanyId());
        if (entityXfSignNo == null || entityXfSignNo.getStatus() == 0) {
            String sJson = HttpUtils.postJson(payUrl + "/ccb/customer/creation.do", map);
            JSONObject results = JSON.parseObject(sJson);

            log.info("未签约 /ccb/customer/creation.do返回信息: " + sJson);
            if (results.getInteger("code") != 200) {
                return new Result(results.getInteger("code"), results.getString("msg"), null);
            } else {
                JSONArray jsonArray = results.getJSONArray("data");
                if (jsonArray.size() == 0) {
                    return new Result(500, "/creation.do 返回信息: " + sJson, null);
                }
                JSONObject date = jsonArray.getJSONObject(0);
                String CUST_ID = date.getString("CUST_ID");

                EntityXfSignNo xfSignNo = new EntityXfSignNo();
                SignNoHandle signNoHandle = new SignNoHandle();
//                xfSignNo.setSignNo(CUST_ID);
                xfSignNo.setSignNo(signNoHandle.encrypt(CUST_ID, 1L));
                xfSignNo.setFaceOpenId(CUST_ID);
                xfSignNo.setMerchId(0);
                xfSignNo.setPId(request.getPId());
                xfSignNo.setComId(request.getComId());
                xfSignNo.setPayWay(32);
                xfSignNo.setStatus(1);
                xfSignNo.setCreateTime(new Date());
                xfSignNo.setUpdateTime(new Date());
                xfSignNoService.saveOrUpdate(xfSignNo);
                strCustId = CUST_ID;
                xfAccountInfoService.updateSign(request.getComId(), request.getPId(),32,CUST_ID);
            }
        } else if (entityXfSignNo.getStatus() == 1) {
            if (entityPersonnelInfo.getStatus() == 0) {
                map.put("type", "1");
            } else if (entityPersonnelInfo.getStatus() == 1) {
                map.put("type", "0");
            }
            map.put("pCode", entityXfSignNo.getSignNo());
            String sJson = HttpUtils.postJson(payUrl + "/ccb/customer/update.do", map);
            log.info("已签约 /ccb/customer/update.do 返回信息: " + sJson);
            JSONObject results = JSON.parseObject(sJson);
            if (results.getInteger("code") != 200) {
                return new Result(results.getInteger("code"), results.getString("msg"), null);
            }
            strCustId = entityXfSignNo.getSignNo();
        }
//        EntityCardInfo entityCardInfo = xfCardInfoService.selectCardByPid(comId, request.getPId());
        String cardId = "";
//        if(entityCardInfo != null){
//            return ResultUtil.success();
//            cardId = entityCardInfo.getCardNo();
//        }else{
        EntityXfAccountInfo accountInfo = xfAccountInfoService.selectAccountPid(comId, request.getPId());
        if (accountInfo != null) {
            cardId = accountInfo.getAccountNo();
        }else{
            return ResultUtil.success();
        }
//        }
//        if(entityCardInfo.getCardState() == 1 && entityCardInfo.getEndDate().before(new Date())){
//        }
        if (cardId != null || cardId.equals("")) {
            //test_js 统一支付平台 用户卡信息同步接口
            HashMap<String, Object> mapCard = new HashMap<>();
            mapCard.put("companyId", entiyXfMerchPayInfo.getCompanyId());
            mapCard.put("userName", entiyXfMerchPayInfo.getUserName());
            mapCard.put("payPassword", entiyXfMerchPayInfo.getPassword());
            mapCard.put("pCode", strCustId);
            mapCard.put("cardNo", cardId);
            mapCard.put("command", "1");
            String sJson = HttpUtils.postJson(payUrl + "/ccb/customer/syncCard.do", mapCard);
            log.info("卡信息同步 发送信息: {}", mapCard);
            JSONObject results = JSON.parseObject(sJson);
            log.info("卡信息同步 /ccb/customer/syncCard.do 返回信息: " + sJson);
            if (results.getInteger("code") != 200) {
                return new Result(results.getInteger("code"), "统一支付返回信息: " +results.getString("msg"), null);
            }
            boolean bReturn = xfCardInfoService.upateAccountNo(request.getComId(), request.getPId(),cardId);
            return ResultUtil.success(bReturn);
        }
        return ResultUtil.success();
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB, companyId = "comId", isMaster = MasterSlaveEnum.SLAVE)
    public Result ccbzhshDeleteUser(Long comId, CcbzhshAddUserVo request) {
        EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(request.getComId(), 0L);
        if (entiyXfMerchPayInfo == null) {
            ResultUtil.error(ResultEnum.Err_2031);
        }
        EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.getOnePersonInfo(request.getComId(), request.getPId());
        if (entityPersonnelInfo == null) {
            ResultUtil.error(ResultEnum.Err_303);
        }
        boolean bDelete = xfSignNoService.deleteBypId(request.getComId(), entiyXfMerchPayInfo.getMerchId(), request.getPId(), 32, 1);
        if (bDelete) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("companyId", entiyXfMerchPayInfo.getCompanyId());
            map.put("userName", entiyXfMerchPayInfo.getUserName());
            map.put("payPassword", entiyXfMerchPayInfo.getPassword());
            map.put("pCode", entityPersonnelInfo.getPCode());
            String payUrl = companyInfoService.getPayCenterUrl(comId, entiyXfMerchPayInfo.getCompanyId());
            String sJson = HttpUtils.postJson(payUrl + "/ccb/customer/remove.do", map);
            JSONObject results = JSON.parseObject(sJson);
            if (results.getInteger("code") != 200) {
                return new Result(results.getInteger("code"), results.getString("msg"), null);
            }
            return ResultUtil.success(results);
        }
        //?是否也删除本地用户卡信息? 和建行用户卡信息?
        return ResultUtil.success(bDelete);
    }

//    public Result ccbzhshIcenterParam(Long comId, CcbzhshAddUserVo request) {
//        EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(request.getComId(), 0L);
//        if (entiyXfMerchPayInfo == null) {
//            ResultUtil.error(ResultEnum.Err_2031);
//        }
//        return null;
//    }

}
